import axios from 'axios';
const baseUrl=function () {
  if (window.location.host.indexOf('otc.test.kanlian.la') >= 0||window.location.host.indexOf('localhost:80') >= 0) {
    return 'https://otc.test.kanlian.la'
  }
  if (window.location.host.indexOf('www.otcoin.vip') >= 0) {
    let protocolHtml=document.location.protocol;
    if(protocolHtml=='https:'){
      return 'https://www.otcoin.vip'
    }
    if(protocolHtml=='http:'){
      return 'http://www.otcoin.vip'
    }
  }
  return '';
};
const BASE_URL = baseUrl();
const checkResponse = (response) =>{
  if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
    return response.data
  } else {
    return {
      status: -404,
      msg: '网络异常'
    }
  }
};
const checkErr = (res) =>{
  if (res.status === -404) {
    throw new Exception(res.msg)
  }
  if (res.data && (!res.data.success)) {
    throw new Exception(res.data.error_msg)
  }
  return res;
};
const $_ajax = {
  get: (url, params = '') => {
    return axios.get(BASE_URL + url, {
      headers: {
        'Content-Type': 'application/json;charset=UTF-8',
        'lang':'zh'
      }
    }
    ).then((response) => {
      return checkResponse(response)
    }, (res) => {
      return checkErr(res)
    });
  },
  post: (url, data ) => {
    return axios.post(BASE_URL + url,
      (data),{
        headers: {
          'Content-Type': 'multipart/form-data;charset=UTF-8;lang=zh',
          'lang':'zh'
        }
      }
    ).then((response) => {
      return checkResponse(response);
    }, (res) => {
      return checkErr(res)
    });
  }
};
export default {
  install: function(Vue) {
    Object.defineProperty(Vue.prototype, '$_ajax', { value:$_ajax});
  }
}